#!/bin/bash

# 完整测试脚本 - 启动mock服务并运行测试

set -e  # 遇到错误立即退出

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}================================================${NC}"
echo -e "${BLUE}🧪 Spring AI Agent Platform - Complete Test${NC}"
echo -e "${BLUE}================================================${NC}"
echo ""

# 1. 检查Node.js
echo -e "${BLUE}1. Checking dependencies...${NC}"
if ! command -v node &> /dev/null; then
    echo -e "${RED}❌ Node.js not found${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Node.js: $(node -v)${NC}"

# 2. 安装mock服务依赖
echo ""
echo -e "${BLUE}2. Setting up mock services...${NC}"
cd mocks
if [ ! -d "node_modules" ]; then
    echo "   Installing dependencies..."
    npm install --silent
fi
cd ..
echo -e "${GREEN}✅ Mock services ready${NC}"

# 3. 停止已有mock服务
echo ""
echo -e "${BLUE}3. Cleaning up existing mock services...${NC}"
lsof -ti:4000 2>/dev/null | xargs kill -9 2>/dev/null && echo "   Stopped port 4000" || echo "   Port 4000 is free"
lsof -ti:4001 2>/dev/null | xargs kill -9 2>/dev/null && echo "   Stopped port 4001" || echo "   Port 4001 is free"
echo -e "${GREEN}✅ Ports ready${NC}"

# 4. 启动mock服务
echo ""
echo -e "${BLUE}4. Starting mock services...${NC}"
cd mocks
node mock-context-manager.js > /tmp/context-manager.log 2>&1 &
CONTEXT_PID=$!
node mock-tool-manager.js > /tmp/tool-manager.log 2>&1 &
TOOL_PID=$!
cd ..

# 等待服务启动
sleep 3

# 验证服务启动
if curl -s http://localhost:4000/health > /dev/null; then
    echo -e "${GREEN}✅ Context Manager running (PID: $CONTEXT_PID)${NC}"
else
    echo -e "${RED}❌ Context Manager failed to start${NC}"
    cat /tmp/context-manager.log
    kill $CONTEXT_PID $TOOL_PID 2>/dev/null
    exit 1
fi

if curl -s http://localhost:4001/health > /dev/null; then
    echo -e "${GREEN}✅ Tool Manager running (PID: $TOOL_PID)${NC}"
else
    echo -e "${RED}❌ Tool Manager failed to start${NC}"
    cat /tmp/tool-manager.log
    kill $CONTEXT_PID $TOOL_PID 2>/dev/null
    exit 1
fi

# 5. 运行Shell测试
echo ""
echo -e "${BLUE}5. Running shell tests...${NC}"
echo ""

# 确保测试脚本可执行
chmod +x test-simple.sh test-agent-start.sh

# 运行简单测试
echo -e "${YELLOW}Running test-simple.sh...${NC}"
./test-simple.sh
TEST_RESULT=$?

echo ""

if [ $TEST_RESULT -eq 0 ]; then
    echo -e "${GREEN}✅ All tests passed!${NC}"
else
    echo -e "${RED}❌ Some tests failed${NC}"
fi

# 6. 清理
echo ""
echo -e "${BLUE}6. Cleaning up...${NC}"
kill $CONTEXT_PID $TOOL_PID 2>/dev/null
echo -e "${GREEN}✅ Mock services stopped${NC}"

echo ""
echo -e "${BLUE}================================================${NC}"
echo -e "${GREEN}🎉 Test Complete!${NC}"
echo -e "${BLUE}================================================${NC}"
echo ""
echo "Logs available at:"
echo "  - /tmp/context-manager.log"
echo "  - /tmp/tool-manager.log"
echo ""

exit $TEST_RESULT
